<?php
/**
 * Generate the URL for a system or dynamic view
 *
 * @package Concerto
 * @subpackage System
 * @author Jason Raede <jason@torchdm.com>
 */
 
namespace application\system;
use application\utilities\Utility;
class Permalink {
	
	/**
	 * Get the base URL for use in generating permalinks
	 *
	 * @return string
	 */
	protected static function getBaseURL() {
		if(getOption('browsing_method') == 'ajax')
			return CN_URL . '#/';
		else
			return CN_URL;
	}
	
	/**
	 * Generate a permalink for a system page
	 *
	 * @return string
	 */
	public static function systemPermalink($type, $id = null) {
		switch($type) {
			case 'dashboard':
				$return = self::getBaseURL() . 'user';
				break;
				
		}
		return $return;
	}
	
	/**
	 * Generate a permalink according to resource type and id
	 *
	 * @param string $resourceType 'content', 'tag', or 'type'
	 * @param int $id The database ID of the object
	 * @return string The generated URL
	 */
	public static function buildPermalink($resourceType, $id) {
		$prettyPermalinks = TRUE;
		
		switch($resourceType) {
			case 'content':
				if($prettyPermalinks) {
					return self::buildContentPermalink($id);
				}
				else {
					return CN_URL.'?display=content&id='.$id;
				}
				break;
			case 'tag':
				if($prettyPermalinks) {
					return self::buildTagPermalink($id);
				}
				else {
					return CN_URL.'?display=content&tags='.$id;
				}
				break;
			case 'type':
				if($prettyPermalinks) {
					return self::buildTypePermalink($id);
				}
				else {
					return CN_URL.'?display=content&type='.$id;
				}
				break;
		}
		Utility::triggerError('Permalink resource type not recognized.');
		
	}
	
	/**
	 * Generate a permalink for a content type
	 *
	 * @param int $id
	 * @return string The generated URL
	 */
	public static function buildTypePermalink($id) {
		$row = DB()->getRow("SELECT * FROM `cn_content_types` WHERE `ct_id`='$id'");
		$contentType = $row->ct_id;
		$permalinkStructure = unserialize(getOption('c'.$contentType.'_browsing_permalink_structure'));
		$renderedPermalink = array();
		foreach($permalinkStructure as $structure) {
			$renderedPermalink[] = self::generatePermalinkFromStructure($structure, 'type', $row);

		}
		if(getOption('browsing_method') == 'ajax')
			return CN_URL.'#/'.implode('/', $renderedPermalink);	
		else
			return CN_URL.implode('/', $renderedPermalink);	
	}
	
	/**
	 * Reverse through all URL parts until we reach a content permalink that
	 * isn't in the current content's ancestry
	 *
	 * @param int $content Type
	 * @param string $previous Previous match in recursion
	 * @return string
	 */
	public static function getMatchingGeneologyUrl($contentType, $previous = '') {
		
		/** First, get all content types that can be parents of the content type */
		$allowedParents = unserialize($concerto->getOption('c'.$contentType.'_allowed_parents'));
		
		/** Now, get the nearest-to-last url portion that is of an allowed parent type */
		$urlInfo = array_reverse($concerto->UrlInterpreter->urlInfo);
		$urlMatch = FALSE;
		foreach($urlInfo as $path) {
			if(in_array($path['type'], $allowedParents)) {
				$urlMatch = $path;
				break;
			}
		}
		if($urlMatch) {
			$previous = $path['url'].'/'.$previous;
			return self::getMatchingGeneologyUrl($path['type'], $previous);
		}
		else {
			return $previous;
		}
	}
	
	/**
	 * Generate the permalink of a content tracing its ancestry all the way back
	 *
	 * @param int $id
	 * @param string $current The current URL string in recursion
	 * @return string The generated URL
	 */
	public static function getAncestralOrigins($id, $current = '') {
		$parent = DB()->getVar("SELECT `content_parent` FROM `cn_content` WHERE `content_id`='$id'");
		if($parent) {
			$permalink = DB()->getVar("SELECT `content_permalink` FROM `cn_content` WHERE `content_id`='$parent'");
			if($current)
				$current = $permalink . '/' . $current;
			else $current = $permalink;
			return self::getAncestralOrigins($parent, $current);
		}
		else {
			return $current;
		}
	}
	
	/**
	 * Generate a permalink portion with a specific structure
	 *
	 * @param string $structure The permalink structure to use in generation
	 * @param string $type The resource type
	 * @param stdClass $row The database row corresponding to the object in question
	 * @return string
	 */
	public static function generatePermalinkFromStructure($structure, $type, $row) {
		switch($structure['name']) {
			case 'content_identifier':
				if($structure['option'] == 'id') return $row->content_id;
				else return $row->content_permalink;
				break;
			case 'content_type':
				switch($type) {
					case 'tag':
						return DB()->getVar("SELECT `ct_permalink` FROM `cn_content_types` WHERE `ct_id`='".$row->tag_content_type."'");
						
						break;
					case 'type':
						return $row->ct_permalink;
						break;
					case 'content':
						return DB()->getVar("SELECT `ct_permalink` FROM `cn_content_types` WHERE `ct_id`='".$row->content_type."'");
						break;
				}
				break;
			case 'year':
				return $row->year;
				break;
			case 'month':
				$monthNames = array(
					1=>'january',
					2=>'february',
					3=>'march',
					4=>'april',
					5=>'may',
					6=>'june',
					7=>'july',
					8=>'august',
					9=>'september',
					10=>'october',
					11=>'november',
					12=>'december'
				);
				if($structure['option'] == 'three-letter') {
					return substr($monthNames[$row->month], 0, 3);
				}
				else {
					return $monthNames[$row->month];
				}
				break;
			case 'day':
				return $row->day;
				break;
			case 'tag_name':
				return $row->tag_permalink;
				break;
			case 'first_tag':
				return DB()->getVar("SELECT `tag_permalink` FROM `cn_tags` INNER JOIN `cn_content_tag_relations` ON `tag_id`=`ctr_tag` WHERE `ctr_content`='".$row->content_id."' ORDER BY `ctr_id` LIMIT 1");
				break;
			case 'first_tag_from_group':
				return DB()->getVar("SELECT `tag_permalink` FROM `cn_tags` INNER JOIN `cn_content_tag_relations` ON `tag_id`=`ctr_tag` WHERE `ctr_content`='".$row->content_id."' AND `tag_group`='".$structure['option']."' ORDER BY `ctr_id` LIMIT 1");
				break;
			case 'parent':
				if($row->content_parent) return DB()->getVar("SELECT `content_permalink` FROM `cn_content` WHERE `content_id`='$row->parent'");
				else return FALSE;
				break;
			case 'geneology':
				if($type == 'content') {
					// Get as far back as the ancestry goes
					return self::getAncestralOrigins($row->content_id);
					
				}
				else {
					if($type == 'tag') $contentType = $row->tag_content_type;
					
					else $contentType = $row->ct_id;
					if($structure['option'] == 'parent') {
						return self::getMatchingGeneologyUrl($contentType);
					}
					else {
	
						/** Links are dynamic, according to current url path information. */
						/** First, get all content types that can be parents of the tag's content type */
						$allowedParents = unserialize($concerto->getOption('c'.$contentType.'_allowed_parents'));
						/** Then get all allowed grandparents */
						$allowedGrandparents = array();
						foreach($allowedParents as $parent) {
							$grandparents = unserialize($concerto->getOption('c'.$parent.'_allowed_parents'));
							if($grandparents) $allowedGrandparents = array_merge($allowedGrandparents, $grandparents);
						}
						
						/** Now, get the nearest-to-last url portion that is of an allowed grandparent type */
						$urlInfo = array_reverse($concerto->UrlInterpreter->urlInfo);
						$urlMatch = FALSE;
						foreach($urlInfo as $path) {
							if(in_array($path['type'], $allowedGrandparents)) {
								$urlMatch = $path;
								break;
							}
						}
						if($urlMatch) {
							return self::getMatchingGeneologyUrl($path['type'], '');
						}
						
					}
				}
				return FALSE;
				break;
				
		}
	}
	
	/**
	 * Generate a permalink for a content object
	 *
	 * @param int $id
	 * @return string
	 */
	public static function buildContentPermalink($id) {
		$row = DB()->getRow("SELECT *, YEAR(`content_timestamp`) AS `year`, MONTH(`content_timestamp`) AS `month` FROM `cn_content` WHERE `content_id`='$id'");
		$contentType = $row->content_type;
		$permalinkStructure = unserialize(getOption('c'.$contentType.'_single_permalink_structure'));
		$renderedPermalink = array();
		foreach($permalinkStructure as $structure) {
			$renderedPermalink[] = self::generatePermalinkFromStructure($structure, 'content', $row);

		}
		if(getOption('browsing_method') == 'ajax')
			return CN_URL.'#/'.implode('/', $renderedPermalink);	
		else
			return CN_URL.implode('/', $renderedPermalink);
		
	}
	
	/**
	 * Generate a permalink for a tag
	 *
	 * @param int $tag The database ID
	 * @return string
	 */
	public static function buildTagPermalink($tag) {
		global $concerto;
		$row = $concerto->DB->getRow("SELECT * FROM `cn_tags` WHERE `tag_id`='$tag' AND `tag_type`!='group'");
		
		$contentType = $row->tag_content_type;
		$permalinkStructure = unserialize(getOption('c'.$contentType.'_tag_permalink_structure'));
		$tagStructures = array();
		foreach($permalinkStructure as $tagStructure) {
			$tagStructures[$tagStructure['id']] = $tagStructure['structures'];
		}
		$renderedPermalink = array();
		foreach($tagStructures[$row->tag_group] as $structure) {
			$renderedPermalink[] = self::generatePermalinkFromStructure($structure, 'tag', $row);

		}
		if(getOption('browsing_method') == 'ajax')
			return CN_URL.'#/'.implode('/', $renderedPermalink);	
		else
			return CN_URL.implode('/', $renderedPermalink);
	}
	
	
}

?>